#!/usr/bin/python
# -*- coding: utf-8 -*-
import cgi, cgitb
cgitb.enable()

import socket
import re

pcl = re.compile(r"Content-Length: (.+?)\r\n")
def query(userid, passwd):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("222.201.132.68",80))
    def process(request):
        sock.send(request)
        head = ""
        body = ""
        body_len = 0
        while True:
            t = sock.recv(1024)
            if "\r\n\r\n" in t:
                loc = t.find("\r\n\r\n")
                head += t[:loc+2]
                body += t[loc+4:]
                break
            else:
                head += t
        m = pcl.search(head)
        body_len = int(m.group(1))
      
        while (body_len!=len(body)):
            body += sock.recv(1024)

        return head, body

    get_str = """GET / HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com

"""
    head, _ = process(get_str)
    url = ""
    for line in head.split("\r\n"):
        if line.startswith("Location"):
            url = line.split(": ")[1]
            break
    urlbase = url[:-14]

    get_str = """GET %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com

""" % url
    _, body = process(get_str)
    __VIEWSTATE = body.split('__VIEWSTATE" value="')[1].split('" />')[0].replace("+", "%2B")
    form = "TextBox1=%s&TextBox2=%s&__VIEWSTATE=%s&RadioButtonList1=%s&Button1=&lbLanguage=" % (userid, passwd, __VIEWSTATE, "%E5%AD%A6%E7%94%9F")
    post_str = """POST %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: %d

%s
""" % (url, len(form), form)
    process(post_str)
    url = urlbase + "/xs_main.aspx?xh=%s" % (userid)
    get_str = """GET %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com

""" % (url)
    _, body = process(get_str)
    username = body.split('"xhxm">')[1].split('</span>')[0].split("  ")[1][:-4]
    url = urlbase + "/xscjcx.aspx?xh=%s&xm=%s&gnmkdm=N121605" % (userid, username)
    get_str = """GET %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com
Referer: http://jw2005.scuteo.com

""" % (url)

    _, body = process(get_str)

    __VIEWSTATE = body.split('__VIEWSTATE" value="')[1].split('" />')[0].replace("+","%2B")

    form = "__VIEWSTATE=%s&btn_zcj=%s" % (__VIEWSTATE, "%C0%FA%C4%EA%B3%C9%BC%A8") 
    post_str = """POST %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com
Referer: http://jw2005.scuteo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: %s

%s
""" % (url, len(form), form)
    html = process(post_str)[1]
    sock.close()
    table = html.split('tr class="datelisthead">')[1].split('</table>')[0].replace('<tr class="alt">', '<tr>').strip()[0:-5].replace("&nbsp;", "")
    trs = map(str.strip, table.split('</tr><tr>'))[1:]
    subjects = {}
    for tr in trs:
        tds = tr[4:-5].split('</td><td>')
        subjects[tds[2]]= [tds[3],tds[8]]

    return subjects
    
if __name__=="__main__":
    import time
    t = time.time()
    form = cgi.FieldStorage()

    userid = form.getvalue('userid')
    passwd = form.getvalue('passwd')
    print "Content-Type: text/html"
    print
    subjects = query(userid, passwd)
    print "<table>"
    for key,value in subjects.items():
        print "<tr>"
        print "<td>%s</td>" % key 
        print "<td>%s</td>" % value[0] 
        print "<td>%s</td>" % value[1]
        print "</tr>"
    print "</table>"
    print time.time()-t

#cgi.print_environ()


